//
// Created by yinlijun on 17-9-30.
//
#include <android/looper.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/un.h>
#include <sys/select.h>
#include <sys/types.h>
#include <pthread.h>

#include "rocky_client.h"
#include "../utils/connection_utils.h"
#include "../utils/app_sys_log.h"
#include "../utils/record_stream.h"
#include "../works/work_item_queue.h"
#include "../utils/write_data_record.h"
#include "../common/rocky_connection.h"
#include "../common/rocky_connection.h"
struct RockyClient{
    RockyConnection *connection;
};

static void rocky_client_handler_write(RockyClient* thiz);

RockyClient* rocky_client_create(size_t buf_size, on_received_data on_received,
                                 on_connection_disconnected on_disconnected) {
    int socket = socket_local_client("rockysocket", SOCK_STREAM);
    if(socket < 0) {
        return NULL;
    }
    RockyClient* thiz = (RockyClient *)malloc(sizeof(RockyClient));
    thiz->connection = (RockyConnection *)rocky_connection_create(socket, buf_size, on_received, on_disconnected);
    app_sys_error("client connection create done: %p", thiz->connection);
    return thiz;
}

int rocky_client_loop(RockyClient *thiz) {
    if(thiz == NULL || thiz->connection == NULL) {
        app_sys_error("client has not setup");
        return -1;
    }

    rocky_connection_loop(thiz->connection);
}

void rocky_client_write_data(RockyClient *thiz, void* data, size_t data_size) {
    rocky_connection_write_data(thiz->connection, data, data_size);
}

int rocky_client_destroy(RockyClient *thiz) {
    if(thiz != NULL) {
        if (thiz->connection != NULL) {
            rocky_connection_shutdown(thiz->connection);
            rocky_connection_destroy(thiz->connection);
        }
        thiz->connection = NULL;
        free(thiz);
    }
}